<script setup lang="ts">
import { useDeleteSeal, useGetAuthUrl, useGetSealList } from '@fl/api/supplier'
import { SearchTable } from '@fl/components'
import type { VxeGridProps, VxePagerEvents } from 'vxe-table'
import { cloneDeep } from 'lodash-es'
import { useMessage } from '@fl/hooks/web/use-message'
import Add from './add.vue'
// import { useUserStore } from '@fl/store/modules/user'

const sealType = ref({
    1: '公章',
    2: '合同专用章',
    3: '财务专用章',
    4: '人事专用章',
    5: '法定代表人章',
    6: '其他',
})

const sealStatus = ref({
    1: '已启用',
    2: '待审核',
    3: '审核不通过',
    4: '挂起',
})

const imgUrl = ref<string>('')

const type = ref<number>(1)

const visible = ref<boolean>(false)

const { createConfirmModal } = useMessage()

// const roleName = computed(() => useUserStore().getUserInfo?.sysUser?.roles[0]?.roleName || '')

// const redirectUrl = roleName.value === '供应商' ? '/supplier-pages/enterprise-management/seal-management' : '/purchase-pages/purchase-enterprise-management/seal-management'
const redirectUrl = location.href

const authUrlParams = computed(() => ({
    redirectUrl,
    flag: true,
}))
const { data } = useGetAuthUrl(authUrlParams)

const initialPage = {
    currentPage: 1,
    pageSize: 10,
    total: 0,
}

const tablePage = ref(cloneDeep(initialPage))

const params = computed(() => ({
    page: tablePage.value.currentPage,
    size: tablePage.value.pageSize,
}))

const { data: tableData, isLoading } = useGetSealList(params)
const { mutate: delSealMutate } = useDeleteSeal()

const gridOptions = reactive<VxeGridProps>({
    align: 'center',
    columnConfig: {
        resizable: true,
    },
    columns: [
        { fixed: 'left', title: '序号', type: 'seq', width: 50 },
        { field: 'sealName', title: '印章名称' },
        { field: 'sealType', slots: { default: 'sealType' }, title: '印章类型' },
        { field: 'platType', title: '平台类型' },
        { field: 'status', slots: { default: 'status' }, title: '状态' },
        { slots: { default: 'operate' }, title: '操作' },
    ],
    data: [],
    editConfig: {
        mode: 'row',
        showStatus: true,
        trigger: 'manual',
    },
    height: 800,
    keepSource: true,
    showOverflow: true,
    toolbarConfig: {
        slots: {
            buttons: 'toolbar_buttons',
        },
    },
})

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.value.currentPage = currentPage
    tablePage.value.pageSize = pageSize
}

const records = ref()
watchEffect(() => {
    if (tableData.value) {
        records.value = cloneDeep(tableData.value.records)
        tablePage.value.total = tableData.value.total ?? 0
    }
})

function add(e) {
    if (!data.value.isAuthorized) {
        createConfirmModal({ content: '请先进行电子签章授权？', confirmButtonText: '去授权', onError: () => {
            console.log('操作取消！')
        }, onSuccess: () => {
            window.open(data?.value.authUrl, '_self')
        } })
    }
    else {
        type.value = e
        visible.value = true
    }
}

// 查看
function goToShow(row: any) {
    imgUrl.value = row.sealImageUrl || ''
}

function del(row: any) {
    const params = {
        orgId: row.orgId,
        sealId: row.sealId,
    }
    createConfirmModal({ content: '是否确认删除？', onError: () => {
        console.log('操作取消！')
    }, onSuccess: () => {
        delSealMutate(params, {
            onSuccess: () => {
                ElMessage.success('删除成功')
            },
        })
    } })
}
</script>

<template>
    <ElCard shadow="never">
        <SearchTable v-bind="gridOptions"
                     v-model:pager="tablePage"
                     row-class-name="table-row-style"
                     :loading="isLoading"
                     :data="records"
                     @page-change="handlePageChange"
        >
            <template #toolbar_buttons>
                <div class="w-full">
                    <el-row>
                        <el-col :span="12">
                            <ElButton type="primary"
                                      @click="add(1)"
                            >
                                新增公司章
                            </ElButton>

                            <ElButton type="primary"
                                      @click="add(2)"
                            >
                                新增法人章
                            </ElButton>
                        </el-col>
                    </el-row>
                </div>
            </template>

            <template #sealType="{ row }">
                <span>
                    {{ sealType[row.sealType] }}
                </span>
            </template>

            <template #status="{ row }">
                <span>
                    {{ sealStatus[row.status] }}
                </span>
            </template>

            <template #operate="{ row }">
                <span>
                    <el-popover placement="bottom"
                                trigger="click"
                                width="110"
                    >
                        <template #reference>
                            <el-button text
                                       @click="goToShow(row)"
                            >
                                查看
                            </el-button>
                        </template>

                        <el-image v-if="imgUrl"
                                  style="width: 100px; height: 100px"
                                  :src="imgUrl"
                                  :zoom-rate="1.2"
                                  :max-scale="7"
                                  :min-scale="0.2"
                                  :preview-src-list="[imgUrl]"
                                  :initial-index="4"
                                  fit="contain"
                        />
                    </el-popover>
                </span>

                <el-button v-if="row.status === 1"
                           text
                           type="primary"
                           @click="del(row)"
                >
                    删除
                </el-button>
            </template>
        </SearchTable>
    </ElCard>

    <Add v-model:visible="visible"
         :type="type"
         :redirect-url="redirectUrl"
    />
</template>

<style lang="scss" scoped></style>
